package websocket;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.*;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@WebSocket
public class TalkWithServerHandler {
    //public static ConcurrentMap<Session, String> userMap = new ConcurrentHashMap<Session, String>();
    public static ConcurrentMap<Session,String> userMap = new ConcurrentHashMap<Session, String>();
    public static int userId = 1;


    @OnWebSocketConnect
    public void connected(Session session) {
        userMap.put(session, "User" + userId++);
    }

    @OnWebSocketClose
    public void closed(Session session, int statusCode, String reason) {
        userMap.remove(session);
    }

    /**
     * 单一用户与服务器对话
     *
     * @param session
     * @param message
     * @throws IOException
     */
    @OnWebSocketMessage
    public void message(Session session, String message) {
        try {
            System.out.println("User: " + userMap.get(session));
            System.out.println("Message: " + message);
            // 将用户发的信息原样返回
            session.getRemote().sendString(message);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    @OnWebSocketMessage
    public void handleBinaryMessage(Session session, byte[] buffer, int offset, int length) throws IOException {
        System.out.println("New Binary Message Received");
        session.getRemote().sendBytes(ByteBuffer.wrap(buffer));
    }





}
